package net.zigin.nhi.waste.adapter;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattService;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.utils.StringUtil;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import io.paperdb.Paper;

public class BleDeviceAdapter extends RecyclerView.Adapter<BleDeviceAdapter.ViewHolder> {

    private final List<BleDevice> list;
    private String uuid_service;
    private String uuid_character;
    private Set<String> macSet = new HashSet<>();

    public BleDeviceAdapter(List<BleDevice> list) {
        this.list = list;
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bluetooth_list, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BleDevice bean = list.get(position);

        holder.dev_name.setText(bean.getName());
        holder.mac.setText(bean.getMac());

        boolean isConnected = BleManager.getInstance().isConnected(bean);
        if (isConnected) {
            holder.connect.setVisibility(View.GONE);
            holder.disConnect.setVisibility(View.VISIBLE);
            Constants.BLE_CONNECT_STATE = true;
        } else {
            holder.connect.setVisibility(View.VISIBLE);
            holder.disConnect.setVisibility(View.GONE);
            Constants.BLE_CONNECT_STATE = false;
        }

        holder.connect.setOnClickListener(v -> {
            if (!BleManager.getInstance().isConnected(bean)) {
                BleManager.getInstance().cancelScan();
                connect(bean);
            }
        });

        holder.disConnect.setOnClickListener(v -> {
            if (BleManager.getInstance().isConnected(bean)) {
                BleManager.getInstance().disconnect(bean);
                notifyDataSetChanged();
            }
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    private void connect(BleDevice device) {
        BleManager.getInstance().connect(device, new BleGattCallback() {
            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.i("连接情况", "连接失败！");
                Constants.BLE_CONNECT_STATE = false;
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                Log.i("连接情况", "连接成功！");
                Constants.BLEDEVICE = bleDevice;
                Constants.BLE_CONNECT_STATE = true;

                //连接成功之后将该设备的MAC存进Set集合，然后将Set集合存进数据库
                macSet.add(bleDevice.getMac());
                Log.i("连接设备MAC", bleDevice.getMac());
                for (String s : macSet) {
                    Log.i("set中的数据", s);
                }
                Log.i("set长度", macSet.size()+"");
                Paper.book().write(Constants.BLEMACS, macSet);

                notifyDataSetChanged();
                List<BluetoothGattService> serviceList = gatt.getServices();
                if (bleDevice.getName().contains("Furi")) {
                    uuid_service = serviceList.get(3).getUuid().toString();
                    uuid_character = serviceList.get(3).getCharacteristics().get(0).getUuid().toString();
                }

                if (bleDevice.getName().contains("HC-")) {
                    uuid_service = serviceList.get(2).getUuid().toString();
                    uuid_character = serviceList.get(2).getCharacteristics().get(0).getUuid().toString();
                }

                if (StringUtil.isNotEmpty(uuid_service) && StringUtil.isNotEmpty(uuid_character)) {
                    Paper.book().write(Constants.UUID_SERVICE, uuid_service);
                    Paper.book().write(Constants.UUID_CHARACTER, uuid_character);
                }
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                if (isActiveDisConnected) {
                    Log.i("连接情况", "断开连接");
                    Constants.BLE_CONNECT_STATE = false;
                    notifyDataSetChanged();
                }
            }
        });
    }


    @Override
    public int getItemCount() {
        return list.size();
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {

        private final TextView dev_name;
        private final TextView mac;
        private final Button connect;
        private final Button disConnect;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            dev_name = itemView.findViewById(R.id.dev_name);
            mac = itemView.findViewById(R.id.mac);
            connect = itemView.findViewById(R.id.connect);
            disConnect = itemView.findViewById(R.id.disConnect);
        }
    }
}

